<template>
  <div class="ai-chat-container">
    <div class="chat-header">
      <h1>AI 智能问答</h1>
      <button 
        class="clear-btn" 
        @click="clearChat" 
        :disabled="messages.length === 0"
      >
        清空记录
      </button>
    </div>

    <div class="chat-history" ref="chatHistory">
      <div class="empty-tip" v-if="messages.length === 0">
        输入问题，开始与AI对话吧～
      </div>
      
      <div 
        v-for="(msg, index) in messages" 
        :key="`${msg.timestamp}-${index}`" 
        :class="['message', `message--${msg.sender}`]"
      >
        <div class="loading" v-if="msg.loading">
          思考中<span class="dot-animation">...</span>
        </div>
        <p v-else>{{ msg.text }}</p>
      </div>
    </div>

    <div class="chat-input">
      <input
        type="text"
        v-model="currentMessage"
        @keyup.enter="handleSend"
        :disabled="isLoading"
        placeholder="输入问题后按回车或点击发送..."
      />
      <button 
        @click="handleSend" 
        :disabled="isLoading || !currentMessage.trim()"
      >
        {{ isLoading ? '发送中' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'AiChatView',
  data() {
    return {
      messages: [],
      currentMessage: '',
      apiUrl: '/api/ai/highChat',
      isLoading: false
    };
  },
  methods: {
    async handleSend() {
      const userInput = this.currentMessage.trim();
      if (!userInput || this.isLoading) return;

      // 添加用户消息
      this.messages.push({
        sender: 'user',
        text: userInput,
        timestamp: Date.now(),
        loading: false
      });
      this.currentMessage = '';
      this.scrollToBottom();

      // 发送请求
      this.isLoading = true;
      // 先添加AI加载中消息并记录索引
      const aiLoadingMsgIndex = this.messages.push({
        sender: 'ai',
        text: '',
        timestamp: Date.now(),
        loading: true
      }) - 1;

      try {
        const response = await axios.get(this.apiUrl, {
          params: { message: userInput },
          timeout: 60000
        });

        // 用splice替代$set更新数组（核心修复点）
        this.messages.splice(aiLoadingMsgIndex, 1, {
          sender: 'ai',
          text: response.data || 'AI暂无有效回复',
          timestamp: Date.now(),
          loading: false
        });
      } catch (error) {
        let errorText = '抱歉，AI服务暂时不可用';
        if (error.code === 'ECONNABORTED') errorText = '请求超时，请稍后再试';
        if (error.response?.status) errorText = `服务错误（${error.response.status}），请重试`;

        // 同样用splice更新错误消息
        this.messages.splice(aiLoadingMsgIndex, 1, {
          sender: 'ai',
          text: errorText,
          timestamp: Date.now(),
          loading: false
        });
        console.error('AI请求失败：', error);
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatHistory = this.$refs.chatHistory;
        if (chatHistory) chatHistory.scrollTop = chatHistory.scrollHeight;
      });
    },

    clearChat() {
      if (confirm('确定要清空所有聊天记录吗？')) {
        this.messages = [];
      }
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.ai-chat-container {
  max-width: 850px;
  margin: 30px auto;
  padding: 24px;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  font-family: 'Inter', 'Arial', sans-serif;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chat-header h1 {
  font-size: 20px;
  color: #2d3748;
  margin: 0;
}

.clear-btn {
  padding: 6px 12px;
  font-size: 14px;
  color: #666;
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.clear-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
  background: #fafbfc;
}

.clear-btn:hover:not(:disabled) {
  background: #edf2f7;
  color: #2d3748;
}

.chat-history {
  height: 450px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #ffffff;
  scrollbar-width: thin;
}

.chat-history::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-thumb {
  background: #e2e8f0;
  border-radius: 3px;
}

.empty-tip {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  font-size: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.message {
  margin-bottom: 16px;
  padding: 10px 16px;
  border-radius: 18px;
  max-width: 75%;
  word-wrap: break-word;
  font-size: 15px;
  line-height: 1.5;
}

.message--user {
  background-color: #3182ce;
  color: #ffffff;
  margin-left: auto;
  border-bottom-right-radius: 4px;
}

.message--ai {
  background-color: #f7fafc;
  color: #2d3748;
  margin-right: auto;
  border-bottom-left-radius: 4px;
  border: 1px solid #edf2f7;
}

.loading {
  color: #94a3b8;
  font-size: 14px;
}

.dot-animation span {
  animation: dotFlash 1.4s infinite both;
}

.dot-animation span:nth-child(1) { animation-delay: -0.32s; }
.dot-animation span:nth-child(2) { animation-delay: -0.16s; }

@keyframes dotFlash {
  0%, 80%, 100% { opacity: 0.4; }
  40% { opacity: 1; }
}

.chat-input {
  display: flex;
  gap: 12px;
  align-items: center;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 15px;
  transition: border-color 0.2s;
}

.chat-input input:focus {
  outline: none;
  border-color: #3182ce;
  box-shadow: 0 0 0 2px rgba(49, 130, 206, 0.1);
}

.chat-input input:disabled {
  background: #fafbfc;
  color: #94a3b8;
  cursor: not-allowed;
}

.chat-input button {
  padding: 12px 24px;
  background-color: #3182ce;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 15px;
  transition: background-color 0.2s;
}

.chat-input button:disabled {
  background-color: #94a3b8;
  cursor: not-allowed;
}

.chat-input button:hover:not(:disabled) {
  background-color: #2b6cb0;
}
</style>